package com.koron.standard.bean.query;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jzp
 * @since 2021/9/1
 */
@Data
public class PageQuery<T> {
    /**
     * 每页显示条数，默认 10
     */
    @ApiModelProperty(value="每页显示条数，默认 10")
    protected long pageSize = 10;

    /**
     * 当前页
     */
    @ApiModelProperty(value="当前页")
    protected long page = 1;
    /**
     * 排序字段信息
     */
    @ApiModelProperty(value="排序字段信息")
    protected List<OrderItem> orders = new ArrayList<>();

    /**
     * 是否进行 count 查询
     */
    @ApiModelProperty(value="是否进行 count 查询")
    protected boolean isSearchCount = true;

    public Page<T> convertPage() {
        Page<T> iPage = new Page<>(page, pageSize, isSearchCount);
        orderHandler(orders);
        iPage.getOrders().addAll(orders);
        return iPage;
    }

    private void orderHandler(List<OrderItem> orders) {
        for (OrderItem order : orders) {
            String column = order.getColumn();
            // 防止SQL注入
            if (containsSqlInjection(column)) {
                throw new IllegalArgumentException("包含非法字符");
            }
            String s = StrUtil.toUnderlineCase(column);
            order.setColumn(s);
        }
    }

    public static boolean containsSqlInjection(Object obj) {
        Pattern pattern = Pattern.compile("\\b(and|exec|insert|select|drop|grant|alter|delete|update|count|chr|mid|master|truncate|char|declare|or|union|sleep|load_file|extractvalue|updatexml)\\b|([*;+'%])|^.*[()].*$");
        Matcher matcher = pattern.matcher(obj.toString().toLowerCase());
        return matcher.find();
    }

}
